package com.yjy.util.custom;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.text.SimpleDateFormat;

public class CustomDateFormatValidator implements ConstraintValidator<CustomDateFormat, String> {
    private CustomDateFormat validDateFormat;
    @Override
    public void initialize(CustomDateFormat validDateFormat) {
        this.validDateFormat = validDateFormat;
    }

    @Override
    public boolean isValid(String value, ConstraintValidatorContext constraintValidatorContext) {
        if (value == null || "".equals(value)) {
            return true;
        }

        String format = validDateFormat.format();
        if (value.length() != format.length()) {
            return false;
        }
        
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat(format);
        try {
            return value.equals(simpleDateFormat.format(simpleDateFormat.parse(value)));
        } catch (Exception e){
            return false;
        }
    }
}